/*
 * Copyright (C) 2021 HiHope Open Source Organization .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 *
 * limitations under the License.
 */

#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "iot_errno.h"
#include "hi_pwm.h"
#include "hi_io.h"
#include "../lib/tcp_send.h"

#define     CLK_160M                160000000
#define     IOT_GPIO_IDX_9          9
#define     IOT_GPIO_PWM_FUNCTION   5
#define     IOT_PWM_PORT_PWM0       0

static const uint16_t g_tuneFreqs = 38223;

int alarm_flag = 0;

static void *BeeperMusicTask(const char *arg)
{
    (void)arg;

    printf("BeeperMusicTask start!\r\n");

    hi_pwm_set_clock(PWM_CLK_XTAL);

    while (1)
    {
        if(global_temp > 32){
            alarm_flag = 1;
            IoTPwmStart(IOT_PWM_PORT_PWM0, 50,  CLK_160M/g_tuneFreqs);
            usleep(100000);
            IoTPwmStop(IOT_PWM_PORT_PWM0);
        }
        else{
            alarm_flag = 0;
        }
    }

    return NULL;
}

static void StartBeepMusicTask(void)
{
    osThreadAttr_t attr;

    IoTGpioInit(IOT_GPIO_IDX_9);
    hi_io_set_func(IOT_GPIO_IDX_9, IOT_GPIO_PWM_FUNCTION);
    IoTGpioSetDir(IOT_GPIO_IDX_9, IOT_GPIO_DIR_OUT);
    IoTPwmInit(IOT_PWM_PORT_PWM0);

    IoTWatchDogDisable();

    attr.name = "BeeperMusicTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024;
    attr.priority = osPriorityNormal;

    if (osThreadNew((osThreadFunc_t)BeeperMusicTask, NULL, &attr) == NULL) {
        printf("[LedExample] Falied to create BeeperMusicTask!\n");
    }
}

SYS_RUN(StartBeepMusicTask);